package com.ecube.maintenance.components.activity;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.navisdk.BNaviPoint;
import com.baidu.navisdk.BaiduNaviManager;
import com.baidu.navisdk.comapi.routeplan.RoutePlanParams;
import com.ecube.maintenance.R;
import com.ecube.maintenance.components.application.CCBApplication;
import com.ecube.maintenance.components.widget.SimpleMarker;
import com.ecube.maintenance.pojos.AddressInfo;
import com.ecube.maintenance.utils.Bog;
import com.umeng.analytics.MobclickAgent;

/**
 * 显示当前位置
 */
public class BaiduMapLocActivity extends CustomFragmentActivity {

    MapView mMapView;
    AddressInfo myAddress,dealerAddress;
    public static void displayMyself(Activity a,AddressInfo my,AddressInfo dealerAddress){
        Intent intent = new Intent(a,BaiduMapLocActivity.class);
        intent.putExtra("MyLocation",my);
        intent.putExtra("DealerLocation",dealerAddress);
        a.startActivity(intent);
    }
    public static void displayMyselfFromFragment(Fragment a,AddressInfo my,AddressInfo dealerAddress){
        Intent intent = new Intent(a.getActivity(),BaiduMapLocActivity.class);
        intent.putExtra("MyLocation",my);
        intent.putExtra("DealerLocation",dealerAddress);
        a.startActivity(intent);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        getActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle("商家位置");
        myAddress = (AddressInfo) getIntent().getSerializableExtra("MyLocation");
        dealerAddress = (AddressInfo) getIntent().getSerializableExtra("DealerLocation");
        initView();
    }

    void initView(){
        mMapView = (MapView) findViewById(R.id.baidu_mapview);
        mMapView.getMap().setMapType(BaiduMap.MAP_TYPE_NORMAL);
//        putAddressOnMap(myAddress);
        locationAt(dealerAddress);
//        SimpleMarker myMarker = new SimpleMarker(myAddress);
//        SimpleMarker dealerMarker = new SimpleMarker(dealerAddress);
//        myMarker.putOnMap(mMapView);
//        dealerMarker.putOnMap(mMapView);
    }
    void locationAt(AddressInfo addressInfo){
        if (addressInfo==null)return;
        BaiduMap mBaiduMap = mMapView.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newLatLngZoom(
                new LatLng(addressInfo.getLat(),addressInfo.getLon()),18f);
        mBaiduMap.setMapStatus(mapStatusUpdate);
// 构造定位数据
        MyLocationData locData = new MyLocationData.Builder()
                .accuracy(100)
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(0).latitude(addressInfo.getLat())
                .longitude(addressInfo.getLon()).build();
// 设置定位数据
        mBaiduMap.setMyLocationData(locData);
// 设置定位图层的配置（定位模式，是否允许方向信息，用户自定义定位图标）
        BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
                .fromResource(R.drawable.ic_action_place);
        MyLocationConfiguration config = new MyLocationConfiguration
                (MyLocationConfiguration.LocationMode.NORMAL, true, mCurrentMarker);
        mBaiduMap.setMyLocationConfigeration(config);
//        当不需要定位图层时关闭定位图层
//        mBaiduMap.setMyLocationEnabled(false);
    }


    /**
     * 指定导航起终点启动GPS导航.起终点可为多种类型坐标系的地理坐标。
     * 前置条件：导航引擎初始化成功
     */
    private void launchNavigator2(){
        try{
            AddressInfo from = myAddress;
            AddressInfo to = dealerAddress;

            final Activity activity = this;
            //这里给出一个起终点示例，实际应用中可以通过POI检索、外部POI来源等方式获取起终点坐标
            BNaviPoint startPoint = new BNaviPoint(from.getLon(),from.getLat(),
                    from.getAddress(), BNaviPoint.CoordinateType.BD09_MC);
            BNaviPoint endPoint = new BNaviPoint(to.getLon(),to.getLat(),
                    to.getAddress(), BNaviPoint.CoordinateType.BD09_MC);
            BaiduNaviManager.getInstance().launchNavigator(activity,
                    startPoint,                                      //起点（可指定坐标系）
                    endPoint,                                        //终点（可指定坐标系）
                    RoutePlanParams.NE_RoutePlan_Mode.ROUTE_PLAN_MOD_MIN_TIME,       //算路方式
                    true,                                            //真实导航
                    BaiduNaviManager.STRATEGY_FORCE_ONLINE_PRIORITY, //在离线策略
                    new BaiduNaviManager.OnStartNavigationListener() {                //跳转监听

                        @Override
                        public void onJumpToNavigator(Bundle configParams) {
                            Intent intent = new Intent(
                                    activity,
                                    BNavigatorActivity.class);
                            intent.putExtras(configParams);
                            startActivity(intent);
                        }

                        @Override
                        public void onJumpToDownloader() {
                        }
                    });
        } catch (Exception e) {
            Bog.toast("启动地图导航失败.");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
    }
    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
        MobclickAgent.onResume(this);
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_activity_loc,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        switch (id){
            case R.id.action_navigation:
                launchNavigator2();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

}
